﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using UCL.Forms;
using UCL.Data;

namespace DBKit5.UControls
{
    // 2013-9-18 by sutroon
    public partial class frmGenerateSqlData : Form
    {
        public string TableName { get; set; }
        public IDatabaseHelper Dbh { get; set; }
        public frmGenerateSqlData()
        {
            InitializeComponent();
        }

        private void frmGenerateSqlData_Load(object sender, EventArgs e)
        {
            if (Dbh == null)
            {
                MessageBox.Show("参数有误");
                return;
            }
            this.Text = "生成SQL数据模板 - " + TableName;
            DataTable dt = Dbh.ExecuteDataTable("select top 1 * from " + this.TableName);
            int i = 0;
            foreach (DataColumn c in dt.Columns)
            {
                tbFields.AppendText(string.Format("{0}={1} | ", i, c.ColumnName));
                i++;
            }

        }

        private void btnSave_Click(object sender, EventArgs e)
        {
            if (tbResult.TextLength == 0) return;
            this.ShowSaveFileDialog("Text files (*.txt)|*.txt", fn => { System.IO.File.WriteAllText(fn, tbResult.Text); return "success"; });
        }

        private void btnRun_Click(object sender, EventArgs e)
        {
            if (tbFmtSql.TextLength == 0) return;
            tbResult.Clear();
            string strSearch = tbSearch.Text;
            if (strSearch.Length > 0) strSearch = " where " + strSearch;
            DataTable dt = Dbh.ExecuteDataTable("select * from " + this.TableName + strSearch);
            tbResult.SuspendLayout();
            foreach (DataRow r in dt.Rows)
            {
                tbResult.AppendText(string.Format(tbFmtSql.Text, r.ItemArray));
                tbResult.AppendText(Environment.NewLine);
            }
            tbResult.ResumeLayout();
        }

        private void lnkAllFields_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            DataTable dt = Dbh.ExecuteDataTable("select top 1 * from " + this.TableName);
            StringBuilder sbFields = new StringBuilder(), sbValues = new StringBuilder();
            int i = 0;
            foreach (DataColumn c in dt.Columns)
            {
                sbFields.AppendFormat("{0},", c.ColumnName);
                sbValues.AppendFormat("'{{{0}}}',", i);
                i++;
            }
            tbFmtSql.Text = string.Format("insert into {0} ({1}) values ({2});", TableName, sbFields.ToString().TrimEnd(','), sbValues.ToString().TrimEnd(','));

        }
    }
}
